package com.maodou.core.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.maodou.core.ui.theme.ComponentSizes.ToolbarHeight
import kotlin.math.max


/**
 * 标题对齐方式枚举
 */
enum class TitleAlignment {
    Start,    // 左对齐
    Center,   // 居中对齐
    End       // 右对齐
}


/**
 * 操作按钮数据类
 * 
 * @param icon 图标
 * @param contentDescription 内容描述
 * @param onClick 点击事件
 * @param enabled 是否启用
 */
data class ActionItem(
    val icon: ImageVector,
    val contentDescription: String,
    val onClick: () -> Unit,
    val enabled: Boolean = true
)

/**
 * 溢出菜单项数据类
 * 
 * @param text 文本
 * @param onClick 点击事件
 * @param enabled 是否启用
 * @param leadingIcon 前置图标
 */
data class OverflowMenuItem(
    val text: String,
    val onClick: () -> Unit,
    val enabled: Boolean = true,
    val leadingIcon: ImageVector? = null
)

/**
 * 带操作按钮和溢出菜单的顶部导航栏
 * 
 * @param title 标题文本
 * @param modifier 修饰符
 * @param navigationIcon 导航图标
 * @param onNavigationClick 导航图标点击事件
 * @param actions 操作按钮列表
 * @param overflowItems 溢出菜单项列表
 * @param maxVisibleActions 最大可见操作按钮数量
 * @param backgroundColor 背景颜色（支持透明）
 * @param contentColor 内容颜色
 * @param elevation 阴影高度
 * @param titleAlignment 标题对齐方式
 * @param applyStatusBarPadding 是否应用状态栏内边距（沉浸式布局）
 */
@Composable
fun ActionBar(
    title: String,
    modifier: Modifier = Modifier,
    navigationIcon: ImageVector? = null,
    onNavigationClick: (() -> Unit)? = null,
    actions: List<ActionItem> = emptyList(),
    overflowItems: List<OverflowMenuItem> = emptyList(),
    maxVisibleActions: Int = 3,
    backgroundColor: Color = MaterialTheme.colorScheme.surface,
    contentColor: Color = MaterialTheme.colorScheme.onSurface,
    elevation: Dp = 4.dp,
    titleAlignment: TitleAlignment = TitleAlignment.Start,
    applyStatusBarPadding: Boolean = true
) {
    var showOverflowMenu by remember { mutableStateOf(false) }

    val statusBarHeight = if (applyStatusBarPadding) {
        WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
    } else {
        0.dp
    }

    // 记录左右区域实际占用宽度（像素），用于为标题层设置对称内边距，保证标题基于屏幕居中且不与两侧重叠
    val density = LocalDensity.current
    var leftWidthPx by remember { mutableStateOf(0) }
    var rightWidthPx by remember { mutableStateOf(0) }

    val visibleActions = actions.take(maxVisibleActions)
    val hiddenActions = actions.drop(maxVisibleActions)

    Column {
        // 状态栏占位空间
        if (applyStatusBarPadding) {
            Spacer(modifier = Modifier.height(statusBarHeight))
        }

        // 自定义 AppBar：底层左右区域（导航 + 操作），上层居中标题
        Box(
            modifier = modifier
                .shadow(if (backgroundColor == Color.Transparent) 0.dp else elevation)
                .fillMaxWidth()
                .height(ToolbarHeight)
                .padding(horizontal = 0.dp) // 外层不加水平内边距，保证标题基于屏幕居中
        ) {
            // 背景色层
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(backgroundColor)
                    .padding(0.dp),
            ) { /* 背景容器 */ }

            // 左右操作区域（位于下层）
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(ToolbarHeight),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 左侧：导航按钮容器（测量宽度）
                Box(
                    modifier = Modifier
                        .onSizeChanged { leftWidthPx = it.width },
                    contentAlignment = Alignment.CenterStart
                ) {
                    if (navigationIcon != null && onNavigationClick != null) {
                        IconButton(onClick = onNavigationClick) {
                            Icon(
                                imageVector = navigationIcon,
                                contentDescription = "Navigation",
                                tint = contentColor,
                                modifier = Modifier.size(32.dp)
                            )
                        }
                    }
                }

                // 中间占位，撑开左右
                Box(modifier = Modifier.weight(1f))

                // 右侧：操作按钮 + 溢出菜单（测量宽度）
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.onSizeChanged { rightWidthPx = it.width }
                ) {
                    visibleActions.forEach { action ->
                        IconButton(
                            onClick = action.onClick,
                            enabled = action.enabled
                        ) {
                            Icon(
                                imageVector = action.icon,
                                contentDescription = action.contentDescription,
                                tint = if (action.enabled) contentColor else contentColor.copy(alpha = 0.38f)
                            )
                        }
                    }

                    if (hiddenActions.isNotEmpty() || overflowItems.isNotEmpty()) {
                        Box {
                            IconButton(onClick = { showOverflowMenu = true }) {
                                Icon(
                                    imageVector = Icons.Filled.MoreVert,
                                    contentDescription = "更多选项",
                                    tint = contentColor
                                )
                            }

                            DropdownMenu(
                                expanded = showOverflowMenu,
                                onDismissRequest = { showOverflowMenu = false }
                            ) {
                                // 隐藏的操作按钮
                                hiddenActions.forEach { action ->
                                    DropdownMenuItem(
                                        text = { Text(action.contentDescription) },
                                        onClick = {
                                            action.onClick()
                                            showOverflowMenu = false
                                        },
                                        enabled = action.enabled,
                                        leadingIcon = {
                                            Icon(
                                                imageVector = action.icon,
                                                contentDescription = null
                                            )
                                        }
                                    )
                                }

                                if (hiddenActions.isNotEmpty() && overflowItems.isNotEmpty()) {
                                    HorizontalDivider()
                                }

                                overflowItems.forEach { item ->
                                    DropdownMenuItem(
                                        text = { Text(item.text) },
                                        onClick = {
                                            item.onClick()
                                            showOverflowMenu = false
                                        },
                                        enabled = item.enabled,
                                        leadingIcon = item.leadingIcon?.let { icon ->
                                            {
                                                Icon(
                                                    imageVector = icon,
                                                    contentDescription = null
                                                )
                                            }
                                        }
                                    )
                                }
                            }
                        }
                    }
                }
            }

            // 居中标题层（位于上层，使用两侧最大宽度作为对称内边距，确保不与两侧区域重叠）
            val sidePaddingDp = with(density) { max(leftWidthPx, rightWidthPx).toDp() }
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = sidePaddingDp),
                contentAlignment = when (titleAlignment) {
                    TitleAlignment.Start -> Alignment.CenterStart
                    TitleAlignment.Center -> Alignment.Center
                    TitleAlignment.End -> Alignment.CenterEnd
                }
            ) {
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Medium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    textAlign = when (titleAlignment) {
                        TitleAlignment.Start -> TextAlign.Start
                        TitleAlignment.Center -> TextAlign.Center
                        TitleAlignment.End -> TextAlign.End
                    },
                    color = contentColor
                )
            }
        }
    }
}

@Composable
fun TopBar(
    content: @Composable () -> Unit
){
    val statusBarHeight = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()

    Column {
        // 状态栏占位空间
        Spacer(modifier = Modifier.height(statusBarHeight))

        Box(
            modifier = Modifier.height(ToolbarHeight),
            contentAlignment = Alignment.Center
        ) {
            content()
        }
    }
}

/**
 * 带返回按钮的操作栏
 * 
 * @param title 标题文本
 * @param onBackClick 返回按钮点击事件
 * @param modifier 修饰符
 * @param actions 操作按钮列表
 * @param overflowItems 溢出菜单项列表
 * @param maxVisibleActions 最大可见操作按钮数量
 * @param backgroundColor 背景颜色
 * @param contentColor 内容颜色
 * @param titleAlignment 标题对齐方式
 * @param applyStatusBarPadding 是否应用状态栏内边距（沉浸式布局）
 */
@Composable
fun BackActionBar(
    title: String,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier,
    actions: List<ActionItem> = emptyList(),
    overflowItems: List<OverflowMenuItem> = emptyList(),
    maxVisibleActions: Int = 3,
    backgroundColor: Color = MaterialTheme.colorScheme.surface,
    contentColor: Color = MaterialTheme.colorScheme.onSurface,
    titleAlignment: TitleAlignment = TitleAlignment.Start,
    applyStatusBarPadding: Boolean = false
) {
    ActionBar(
        title = title,
        modifier = modifier,
        navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
        onNavigationClick = onBackClick,
        actions = actions,
        overflowItems = overflowItems,
        maxVisibleActions = maxVisibleActions,
        backgroundColor = backgroundColor,
        contentColor = contentColor,
        titleAlignment = titleAlignment,
        applyStatusBarPadding = applyStatusBarPadding
    )
}

@Preview(showBackground = true)
@Composable
fun ActionBarPreview() {
    MaterialTheme {
        Column {
            // 基础 ActionBar - 左对齐
            ActionBar(
                title = "左对齐标题",
                navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
                onNavigationClick = { },
                actions = listOf(
                    ActionItem(
                        icon = Icons.Default.Search,
                        contentDescription = "搜索",
                        onClick = { }
                    ),
                    ActionItem(
                        icon = Icons.Default.MoreVert,
                        contentDescription = "更多",
                        onClick = { }
                    )
                ),
                titleAlignment = TitleAlignment.Start
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 居中对齐标题
            ActionBar(
                title = "居中标题",
                navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
                onNavigationClick = { },
                actions = listOf(
                    ActionItem(
                        icon = Icons.Default.Search,
                        contentDescription = "搜索",
                        onClick = { }
                    )
                ),
                titleAlignment = TitleAlignment.Center
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 右对齐标题
            ActionBar(
                title = "右对齐标题",
                navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
                onNavigationClick = { },
                actions = listOf(
                    ActionItem(
                        icon = Icons.Default.MoreVert,
                        contentDescription = "更多",
                        onClick = { }
                    )
                ),
                titleAlignment = TitleAlignment.End
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 透明背景
            ActionBar(
                title = "透明背景",
                navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
                onNavigationClick = { },
                actions = listOf(
                    ActionItem(
                        icon = Icons.Default.Search,
                        contentDescription = "搜索",
                        onClick = { }
                    )
                ),
                backgroundColor = Color.Transparent,
                titleAlignment = TitleAlignment.Center
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 半透明背景
            ActionBar(
                title = "半透明背景",
                navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
                onNavigationClick = { },
                actions = listOf(
                    ActionItem(
                        icon = Icons.Default.Edit,
                        contentDescription = "编辑",
                        onClick = { }
                    )
                ),
                backgroundColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.8f),
                titleAlignment = TitleAlignment.Center
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 带溢出菜单的 ActionBar
            ActionBar(
                title = "带溢出菜单",
                navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
                onNavigationClick = { },
                actions = listOf(
                    ActionItem(
                        icon = Icons.Default.Search,
                        contentDescription = "搜索",
                        onClick = { }
                    ),
                    ActionItem(
                        icon = Icons.Default.Edit,
                        contentDescription = "编辑",
                        onClick = { }
                    ),
                    ActionItem(
                        icon = Icons.Default.Share,
                        contentDescription = "分享",
                        onClick = { }
                    ),
                    ActionItem(
                        icon = Icons.Default.Delete,
                        contentDescription = "删除",
                        onClick = { }
                    )
                ),
                overflowItems = listOf(
                    OverflowMenuItem(
                        text = "设置",
                        onClick = { }
                    ),
                    OverflowMenuItem(
                        text = "帮助",
                        onClick = { }
                    )
                ),
                maxVisibleActions = 2
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 沉浸式状态栏 ActionBar
            ActionBar(
                title = "沉浸式操作栏",
                navigationIcon = Icons.AutoMirrored.Filled.ArrowBack,
                onNavigationClick = { },
                backgroundColor = MaterialTheme.colorScheme.primaryContainer,
                titleAlignment = TitleAlignment.Center,
                applyStatusBarPadding = true,
                actions = listOf(
                    ActionItem(
                        icon = Icons.Default.Search,
                        contentDescription = "搜索",
                        onClick = { }
                    ),
                    ActionItem(
                        icon = Icons.Default.Edit,
                        contentDescription = "编辑",
                        onClick = { }
                    )
                )
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun BackActionBarPreview() {
    MaterialTheme {
        BackActionBar(
            title = "详情页面",
            onBackClick = { },
            actions = listOf(
                ActionItem(
                    icon = Icons.Default.Edit,
                    contentDescription = "编辑",
                    onClick = { }
                ),
                ActionItem(
                    icon = Icons.Default.Share,
                    contentDescription = "分享",
                    onClick = { }
                )
            )
        )
    }
}